package cn.tedu.ivos2.geofence.service.impl;

import cn.tedu.ivos2.base.exception.ServiceException;
import cn.tedu.ivos2.base.response.StatusCode;
import cn.tedu.ivos2.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos2.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos2.geofence.pojo.dto.GeofenceSaveParam;
import cn.tedu.ivos2.geofence.pojo.entity.Geofence;
import cn.tedu.ivos2.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos2.geofence.service.GeofenceService;
import cn.tedu.ivos2.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos2.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos2.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> queryGeofence(GeofenceQuery geofenceQuery) {
        return geofenceMapper.queryGeofence(geofenceQuery);
    }

    @Override
    public void deleteGeofence(Long id) {
        log.debug("删除地理围栏：{}", id);
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> list = vehicleMapper.queryVehicleList(vehicleQuery);
        if (!list.isEmpty()){
            throw new ServiceException(StatusCode.VEHICLE_EXISTS);
        } else {
            geofenceMapper.deleteGeofence(id);
        }
    }

    @Override
    public void saveGeofence(GeofenceSaveParam geofenceSaveParam) {
        log.debug("保存地理围栏：{}", geofenceSaveParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam,geofence);
        if (geofence.getId() == null) {
            geofence.setCreateTime(new Date());
            geofence.setStatus("1");
            geofenceMapper.saveGeofence(geofence);
        } else {
            geofence.setUpdateTime(new Date());
            geofenceMapper.updateGeofence(geofence);
        }
    }
}
